var appInstance = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {

    pickup_list:[],
    latLng:{
      lat:'',
      lng:''
    }

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

    this.init();

  },

  init:function( resolve ){

    var t = this;

    this.getLocation();

    var url = appInstance.globalData.api_path + '&r=pickup.get_list';

    appInstance.request(url, {}, 'GET', function( res ){

      t.setData({

        pickup_list : res.data

      },function(){

        t.getLocation();

      });
      if( typeof resolve == 'function'){
        resolve( res.data );
      }



    });

  },



  getLocation:function( callback ){

    var t = this;
    wx.getLocation({
      type: 'wgs84',
      success (res) {

        // const latitude = res.latitude
        // const longitude = res.longitude
        // const speed = res.speed
        // const accuracy = res.accuracy

        t.setData({
          latLng:{
            lat:res.latitude,
            lng:res.longitude
          }
        }, function(){

          t.getPickupDistance();

        });

        console.log( res )

      }
    });
  },

  getPickupDistance:function(){

    var t = this;
    this.data.pickup_list.forEach(function( item ){

      item.distance = t.getDistance( item.latitude, item.longitude, t.data.latLng.lat, t.data.latLng.lng );

      if(item.distance > 1000 ){
        item.distance /= 1000;
        item.distance = item.distance.toFixed(2);
        item.distance += 'km';
      }else{
        item.distance = parseInt( item.distance );
        item.distance += 'm';
      }
      console.log( item.distance );
    });

    this.setData({

      pickup_list: this.data.pickup_list

    });

  },

  toRad : function (d) {
    return d * Math.PI / 180;
  },

  getDistance:function( lat1, lng1, lat2, lng2 ){

    var dis = 0;

    var radLat1 = this.toRad(lat1);
    var radLat2 = this.toRad(lat2);
    var deltaLat = radLat1 - radLat2;
    var deltaLng = this.toRad(lng1) - this.toRad(lng2);
    var dis = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(deltaLat / 2), 2) + Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(deltaLng / 2), 2)));
    return dis * 6378137;

  },

  checkPickup:function( e ){

    var pickup = e.currentTarget.dataset.item;

    wx.setStorageSync('pickup', pickup);
    wx.navigateBack();

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

    var p = new Promise( this.init );
    p.then(function( result ){
      wx.stopPullDownRefresh();
    });
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})